﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.SessionState;

namespace StudentManagerPro.Code
{
    /// <summary>
    /// Code3 的摘要说明
    /// </summary>
    public class Code3 : IHttpHandler, IRequiresSessionState
    {

        //响应请求
        public void ProcessRequest(HttpContext context)
        {
            //【1】创建一个指定大小的空白图片
            Bitmap image = new Bitmap(130, 33);
            Graphics grap = Graphics.FromImage(image);//整个绘图的核心对象（提供一系列绘图的方法或属性）
            grap.Clear(Color.White);//将当前的图片绘制成全白色

            //【2】随机输出噪点
            Random rand = new Random();
            for (int i = 0; i < 100; i++)
            {
                int x = rand.Next(image.Width);
                int y = rand.Next(image.Height);
                grap.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1);
            }

            //【3】输出验证字符表达式 
            Color[] c = { Color.Black, Color.Red,
                            Color.DarkBlue, Color.Green,
                            Color.Orange, Color.Brown, Color.DarkCyan,
                            Color.Purple }; //定义颜色数组          
            string[] font = { "Verdana", "Microsoft Sans Serif",
                                "Comic Sans MS", "Arial", "宋体" };  //定义字体数组      
            Font f = new System.Drawing.Font(font[3], 18, System.Drawing.FontStyle.Bold);
            Brush b = new System.Drawing.SolidBrush(c[5]);
            grap.DrawString(RandomNum(context), f, b, new Point(5, 3));

            //【4】画一个边框
            grap.DrawRectangle(new Pen(Color.Black, 0), 0, 0, image.Width - 1, image.Height - 1);
            //【5】输出到浏览器
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            image.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
            context.Response.ClearContent();
            context.Response.ContentType = "image/gif";
            context.Response.BinaryWrite(ms.ToArray());
            grap.Dispose();
            image.Dispose();
        }
        //生成随机验证表达式
        private string RandomNum(HttpContext context)
        {
            string VNum = string.Empty;
            Random rand = new Random();
            int num1 = 0;
            while (true)
            {
                num1 = rand.Next(20);
                if (num1 >= 10) break;
            }
            VNum = num1.ToString() + " + ";
            int num2 = 0;
            while (true)
            {
                num2 = rand.Next(10);
                if (num2 > 0) break;
            }
            VNum += num2.ToString() + " = ?";
            context.Session["CheckCode"] = num1 + num2; //保存验证码
            return VNum;
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}